package com.cracker.websocket.server.service;

import com.alibaba.fastjson.JSONObject;
import com.cracker.websocket.server.constant.CmdConstant;
import com.cracker.websocket.server.constant.MessageTypeConstant;
import com.cracker.websocket.server.dto.ResponseCmdDto;
import com.cracker.websocket.server.dto.message.ChatMessageDto;
import com.cracker.websocket.server.dto.messagemeta.AudioMessage;
import com.cracker.websocket.server.dto.messagemeta.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;

@Service
@Slf4j
public class ChatService {
    @Autowired
    private MessageService messageService;
    @Autowired
    private SessionService sessionService;

    public void sendMsg(Session session, String targetUserId, ChatMessageDto messageDto) throws IOException {
        // 处理发送消息类型
        switch (messageDto.getMessageType()) {
            case MessageTypeConstant.TEXT:
                TextMessage textMessage = ((JSONObject) messageDto.getMessage()).toJavaObject(TextMessage.class);
                log.warn("发送文本消息 {}", textMessage);
                messageDto.setMessage(textMessage);
                break;
            case MessageTypeConstant.AUDIO:
                AudioMessage audioMessage = ((JSONObject) messageDto.getMessage()).toJavaObject(AudioMessage.class);
                log.warn("发送语音消息 {}", audioMessage);
                messageDto.setMessage(audioMessage);
                break;
        }
        Session targetSession = sessionService.getByUserId(Integer.parseInt(targetUserId));
        if (null != targetSession) {
            // 目标在线
            targetSession.getBasicRemote().sendText(messageService.encode(messageDto));
        } else {
            // TODO 用户离线
        }
        ResponseCmdDto<ChatMessageDto> responseCmdDto = new ResponseCmdDto<>();
        responseCmdDto.setCmd(CmdConstant.CHAT_MSG);
        responseCmdDto.setData(messageDto);
        session.getBasicRemote().sendText(messageService.encode(responseCmdDto));
        // TODO 持久化聊天数据
    }
}
